import {reactive,ref} from 'vue'
import request from '@/base/request'
import { ElMessage, FormRules } from 'element-plus'
export default function(){

    interface registerParm {
        username:string,
        password:string,
        realname:string,
        email:string,
        code:string,
        id:string
    }

    const openRegister=ref<boolean>(false)
    
    const registerParm=ref<registerParm>({
        username: "",
        password: "",
        realname:"",
        email:"",
        code:"",
        id:""
    })

    const rules = reactive<FormRules<registerParm>>({
        username: [
          { required: true, message: 'Please enter user name', trigger: 'blur' },
          { min: 3, max: 15, message: 'Length should be 3 to 15', trigger: 'blur' },
        ],
        password: [
            { required: true, message: 'Please enter password', trigger: 'blur' },
            { min: 6, max: 30, message: 'Length should be 6 to 30', trigger: 'blur' },
        ],
        realname: [
            { min: 0, max: 20, message: 'Length should be 0 to 20', trigger: 'blur' },
        ],
        email: [  
            { type: 'email', message: 'Please enter a valid email address', trigger: ['blur', 'change'] },  
        ],
    })


    async function doRegister() {
        const response=await request.post(`/user/doRegister`,registerParm.value)
        if(response.data.code===200){
            ElMessage.success("注册成功")
            setTimeout(()=>{
                location.reload()
            },600)
            
        }else{
            ElMessage({
                message:`注册失败：${response.data.msg}`,
                grouping:true,
                type:'error'
            })
        }
    }

    async function getEmailCode() {
        const response=await request.get(`/user/getEmailCode?email=${registerParm.value.email}`)
        if(response.data.code===200){
            ElMessage.success("发送成功")
        }else{
            ElMessage({
                message:`发送失败：${response.data.msg}`,
            })
        }
    }

    return {rules,openRegister,registerParm,getEmailCode,doRegister}
}